from fastapi import APIRouter
from fastapi.responses import JSONResponse,FileResponse
from pydantic import BaseModel

router = APIRouter()

# 响应的模型
class Message(BaseModel):
    message: str

class Item(BaseModel):
    id: str
    value: str

@router.get("/items/{item_id}",response_model=Item,responses={404: {"model": Message}})
async def read_item(item_id: str):
    if item_id == "phone":
        return {"id": "phone", "value": "12345678"}
    return JSONResponse(status_code=404, content={"message": "Item not found"})

@router.get("/info",
            response_model=Item,
            responses={
                200: {
                    "content": {"image/png": {}},
                    "description": "Returns an image"
                }
            })
async def get_info(img: bool | None = None):
    if img:
        return FileResponse("../statics/image.png", media_type="image/png")
    else:
        return JSONResponse(status_code=200, content={"message": "Hello World"})


class Order(BaseModel):
    order_no: str
    amount: float

@router.get("/order/{order_id}",
            response_model=Order,
            responses={
                404:{"model": Message,"description": "the order not found"},
                200: {
                    "description": "order requested by id",
                    "content": {
                        "application/json": {
                            "example": {"order_no": "123456", "amount": 100.0}
                        }
                    }
                }
            }
            )
async def read_order(order_id: int):
    if order_id == 1:
        return {"order_no": "123456", "amount": 100.0}
    else:
        return JSONResponse(status_code=404, content={"message": "order not found"})



# 预定义响应
responses = {
    404: {"description": "not found"},
    302: {"description": "was moved"},
    403: {"description": "forbidden"},
}

@router.get("/order_query/{order_no}",
            response_model=Order,
            responses={**responses, 200: {"content": {"image/png": {}}}}
            )
async def read_order(order_no: str,img: bool | None = None):
    if img:
        return FileResponse("../statics/image.png", filename="new_imgae.png", media_type="application/octet-stream")
    else:
        return Order(order_no=order_no,amount=1999.9)